package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;

public class MainAbilitySlice extends AbilitySlice {

    Button enter_newAbilitySlice;
    Button enter_second;
    Text backValueText;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        enter_newAbilitySlice = findComponentById(ResourceTable.Id_enter_newAbilitySlice);
        enter_second = findComponentById(ResourceTable.Id_enter_second);
        backValueText = findComponentById(ResourceTable.Id_main_text);

        setOnClick();
    }

    /**
     * 设置点击事件
     */
    private void setOnClick() {

        //AbilitySlice之间跳转
        enter_newAbilitySlice.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                presentForResult(new NewAbilitySlice(), new Intent(), 102);

            }
        });

        //ability之间跳转
        enter_second.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                startEnterSecondAbility();
            }
        });
    }


    //abiliyeSlice 跳转到Ablility
    private void startEnterSecondAbility() {
        Intent intent = new Intent();
        //指定那个Ablibity
        Operation operation = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName("com.example.myapplication.SecondAbility")
                .build();
        intent.setOperation(operation);

        intent.setParam("key", "我从MainAbility进到了SecondAbility");
        startAbilityForResult(intent, 1);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {

        if (requestCode == 102) {
            if (null != resultIntent) {
                String result = resultIntent.getStringParam("key");
            }
        }
        super.onResult(requestCode, resultIntent);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (resultCode != 0 || resultData == null) {
            return;
        }
        String result = resultData.getStringParam("key");
        backValueText.setText(result);
    }
}
